/**
 * Created by DevilsEyes on 2016/4/19.
 */
'use strict';
//提供和公告相关的接口
//管理员和普通接口全部放在这里。

var $model = require('../db/notice');

let filter = function (o) {
    return {
        _id: o._id,

        title: o.title,//标题
        article: o.article,//内容
        class: o.class || '',//班级  A#B#C#D
        created: o.created//发布时间
    }
};

module.exports = {

    //获取列表
    getList(ClassStr){
        return new Promise((O, X)=> {

            let query = ClassStr ?
                $model.where('class', new RegExp(`(^|#)${ClassStr}($|#)`))
                :
                $model.find({});

            query.then((notices)=> {
                if (notices) {
                    O(notices.map((o)=>filter(o)));
                } else {
                    throw {
                        code: 9999,
                        msg: '发生了一些错误'
                    }
                }
            });
        });
    },
    
    //查询某个
    getOnebyId(id){
        return new Promise((O, X)=> {
            $model
                .find({_id: id})
                .then((homeworks)=> {
                    if (homeworks) {
                        O(filter(homeworks[0]));
                    } else {
                        throw {
                            code: 9999,
                            msg: '未找到该课件'
                        }
                    }

                });
        })
    },

    //新建
    save: (obj) => {
        return new Promise((O, X)=> {
            obj.created = new Date().getTime();
            var Entity = new $model(obj);
            Entity.save(()=> {
                O();
            })
        })
    },

    //编辑
    update: (id, o)=> {
        return new Promise((O, X)=> {
            var Entity = {
                title: o.title,//标题
                class: o.class || '',//班级  A#B#C#D
                article: o.article || ''//描述
            };

            $model
                .find({_id: id})
                .update(Entity)
                .then(()=> {
                    O();
                })
        })
    },

    //删除
    deleteById: (id)=> {
        return new Promise((O, X)=> {
            $model
                .remove({_id: id})
                .then(()=> {
                    O();
                })
        })
    },

//******************************************
//                 危险!
//******************************************
    //删除全部
    clear: () => {
        return new Promise((O, X)=> {
            $model
                .remove({})
                .then(()=> {
                    O();
                });
        })
    }
};